package edu.rakovic.elearning.pages;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.ioc.annotations.Inject;

import edu.rakovic.elearning.enums.Role;
import edu.rakovic.elearning.interfaces.User;
import edu.rakovic.elearning.service.Users;

public class EditUser {
	
	@Inject
	private Users users;

	//required for login check
	@SessionState
	private User user;

	private boolean userExists;
	
	public User getUser() {
		return user;
	}
	
	//required for user edit
	@Property
	private User userEdit;
	
	private String exclude;

	private String userName = "";

	public void onActivate(String userName) {
		userEdit = users.retreiveSingleUser(userName);
		this.userName = userName;
	}
	
	public String onPassivate() {
		return userName;
	}
	
	
	public Object onSuccess() {
		users.save(userEdit);
		return ViewUsers.class;
	}

	
	//check user
	Object onActivate() {
		if (!userExists) return Login.class;
		if (!checkUser()) {
			return Index.class;
		}
		return null;
	}
	
	public boolean checkUser(){
		Role role = getUser().getRole();
		String un1 = userEdit.getUserName();
		String un2 = getUser().getUserName();
		if(role != Role.ADMINISTRATOR && ! un1.equalsIgnoreCase(un2))
			return false;
		return true;
	}

	public void setExclude(String exclude) {
		this.exclude = exclude;
	}

	public String getExclude() {
		if (getUser().getRole()== Role.ADMINISTRATOR)
			return "userName";
		else return "userName,role";
	}

}
